package com.jhl.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhl.seckill.entity.Order;
import com.jhl.seckill.entity.SeckillGoods;
import com.jhl.seckill.entity.SeckillOrder;
import com.jhl.seckill.entity.User;
import com.jhl.seckill.mapper.OrderMapper;
import com.jhl.seckill.service.GoodsService;
import com.jhl.seckill.service.OrderService;
import com.jhl.seckill.service.SeckillGoodsService;
import com.jhl.seckill.service.SeckillOrderService;
import com.jhl.seckill.utils.MD5Util;
import com.jhl.seckill.utils.UUIDUtil;
import com.jhl.seckill.vo.GoodsVo;
import com.jhl.seckill.vo.OrderDetailVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author JHL
 * @since 2022-04-28
 */
@Service
@Primary
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    GoodsService goodsService;

    @Autowired
    SeckillOrderService seckillOrderService;

    @Autowired
    SeckillGoodsService seckillGoodsService;

    @Override
    public Order seckill(User user, GoodsVo goodsVo) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        SeckillGoods seckillGoods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goodsVo.getId()));

//        boolean seckillGoodsResult = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>()
//                .setSql("stock_count = " + "stock_count-1")
//                .eq("goods_id", goodsVo.getId())
//                .gt("stock_count", 0));
        if (seckillGoods.getStockCount() < 1) {
//            redis中放置库存为0的key
            valueOperations.set("isStockEmpty:" + goodsVo.getId(), "0");
            return null;
        }
//        生成订单
        Order order = new Order();

        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate((new Date()));
        log.info("插入订单");
        orderMapper.insert(order);

        SeckillOrder SeckillOrder = new SeckillOrder();
        SeckillOrder.setUserId(user.getId());
        SeckillOrder.setOrderId(order.getId());
        SeckillOrder.setGoodsId(goodsVo.getId());
        seckillOrderService.save(SeckillOrder);
//        缓存秒杀订单
        log.info("缓存秒杀订单");
        redisTemplate.opsForValue().set("order:" + user.getId() + ":" + goodsVo.getId(), SeckillOrder);
        return order;
    }

    /**
     * 订单详情
     */
    @Override
    public OrderDetailVo detail(Long orderId) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        OrderDetailVo redisOrderDetailVo = (OrderDetailVo) valueOperations.get("order:" + orderId);
        if (redisOrderDetailVo != null) {
            return redisOrderDetailVo;
        }
        Order order = orderMapper.selectById(orderId);
        GoodsVo goodsVo = goodsService.findGoodsVobyGoodsId(order.getGoodsId());
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setOrder(order);
        orderDetailVo.setGoodsVo(goodsVo);

        valueOperations.set("order:" + orderId, orderDetailVo);

        return orderDetailVo;


    }

    @Override
    public String createPath(User user, Long goodsId) {
        String path = MD5Util.md5(UUIDUtil.uuid() + "123456");
        redisTemplate.opsForValue().set("seckillPath:" + user.getId() + ":" + goodsId,
                path, 60, TimeUnit.SECONDS);
        return path;
    }

    //    对秒杀路径进行验证
    @Override
    public boolean checkPath(User user, Long goodsId, String path) {
        if (goodsId < 0 || StringUtils.isEmpty(path)) {
            return false;
        }
        String redisPath = (String) redisTemplate.opsForValue().get("seckillPath:" + user.getId() + ":" + goodsId);
        return redisPath.equals(path);
    }

    /**
     * 校验验证码
     */
    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (StringUtils.isEmpty(captcha) || user == null || goodsId < 0) {
            return false;
        }
//        取出redis的验证码进行验证
        String redisCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId);
        return captcha.equals(redisCaptcha);
    }


}
